#include "widget.h"
#include "ui_widget.h"
#include <QFile>
#include <QEventLoop>
#include <QObject>
#include <QDebug>

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget), att(nullptr), mass(nullptr), dist(nullptr)
{
    ui->setupUi(this);
    this->setFixedSize(800, 560);  // 设置窗口大小为 800x600，且不可调整

    // 初始化 dist
    dist = new distinguish(this);
    ui->stackedWidget->addWidget(dist);
    ui->stackedWidget->setCurrentWidget(dist);

    // 网络访问管理器初始化
    manager = new QNetworkAccessManager();
    QString apiKey = "ZY7znIp96Ehrk2auFpm3Ao0O";
    QString secretKey = "xmteAfscDwNS5LOC5eRV2PufEGUKUaUb";
    getAccessToken(apiKey, secretKey);

    // 调用百度 API 注册人脸
    QString imagePath = "C:/Users/22527/Desktop/2.JPG";
    QString userId = "222222222";
    QString groupId = "99";
    QString userInfo = "赵，25，8";
    registerFace(accessToken, imagePath, userId, groupId, userInfo);
}

Widget::~Widget()
{
    delete ui;
    if (manager) {
        manager->deleteLater();
    }
}

// 获取token
void Widget::getAccessToken(const QString &apiKey, const QString &secretKey)
{
    QUrl url("https://aip.baidubce.com/oauth/2.0/token");
    QUrlQuery query;
    query.addQueryItem("grant_type", "client_credentials");
    query.addQueryItem("client_id", apiKey);
    query.addQueryItem("client_secret", secretKey);
    url.setQuery(query);

    QNetworkRequest request(url);
    QNetworkReply *reply = manager->get(request);

    QEventLoop loop;
    connect(reply, &QNetworkReply::finished, &loop, &QEventLoop::quit);
    loop.exec();

    if (reply->error() == QNetworkReply::NoError)
    {
        QString response = reply->readAll();
        QJsonDocument jsonDoc = QJsonDocument::fromJson(response.toUtf8());
        QJsonObject jsonObject = jsonDoc.object();
        accessToken = jsonObject.value("access_token").toString();
        qDebug() << "Access Token:" << accessToken;
    }
    else
    {
        qDebug() << "Error getting access token:" << reply->errorString();
    }
    reply->deleteLater();
}

// 其他百度 API 函数保留...
/*
 *
    管理人脸库接口调用示例
    QString imagePath = "path_to_your_image.jpg";
    QString userId = "your_user_id";
    QString groupId = "your_group_id";
    QString userInfo = "your_user_info";
    QString accessToken = "access_token";
    registerFace(accessToken, imagePath, userId, groupId, userInfo);
 *
*/
//人脸信息注册
void Widget::registerFace(const QString &accessToken, const QString &imagePath, const QString &userId, const QString &groupId, const QString &userInfo)
{
    QUrl url("https://aip.baidubce.com/rest/2.0/face/v3/faceset/user/add");
    QUrlQuery query;
    query.addQueryItem("access_token", accessToken);
    url.setQuery(query);

    QFile *file = new QFile(imagePath);
    if (!file->open(QIODevice::ReadOnly)) {
        qDebug() << "Error opening image file";
        return;
    }

    QByteArray imageBase64 = file->readAll().toBase64();
    file->close();

    QJsonObject json;
    json["image"] = QString(imageBase64);
    json["image_type"] = "BASE64";
    json["group_id"] = groupId;
    json["user_id"] = userId;
    json["user_info"] = userInfo;
    json["quality_control"] = "NORMAL";
    json["liveness_control"] = "NORMAL";

    QJsonDocument jsonDoc(json);
    QByteArray postData = jsonDoc.toJson();

    QNetworkReply *reply = manager->post(QNetworkRequest(url), postData);

    // Wait for the reply
    QEventLoop loop;
    connect(reply, &QNetworkReply::finished, &loop, &QEventLoop::quit);
    loop.exec();
    if (reply->error() == QNetworkReply::NoError)
    {
        QByteArray response = reply->readAll();
        // 解析JSON
        QJsonDocument jsonResponse = QJsonDocument::fromJson(response);
        // 检查是否解析成功
        if (!jsonResponse.isNull())
        {
            // 获取JSON对象
            QJsonObject jsonObject = jsonResponse.object();
            // 提取需要的信息
            QString errorCode = jsonObject.value("error_code").toString();
            QString errorMessage = jsonObject.value("error_msg").toString();
            QString log_id = jsonObject.value("log_id").toString();
            QString face_token = jsonObject.value("face_token").toString();

            // 打印或处理这些信息
            qDebug() << "Error Message:" << errorMessage;
            qDebug() << "Response:" << response;
        } else
        {
            qDebug() << "Error registering face:" << reply->errorString();
        }
    }
    reply->deleteLater();
}

//更新人脸库
void Widget::updateFace(const QString &accessToken, const QString &imagePath, const QString &userId, const QString &groupId, const QString &userInfo)
{
    QUrl url("https://aip.baidubce.com/rest/2.0/face/v3/faceset/user/update");
    QUrlQuery query;
    query.addQueryItem("access_token", accessToken);
    url.setQuery(query);

    QFile *file = new QFile(imagePath);
    if (!file->open(QIODevice::ReadOnly)) {
        qDebug() << "Error opening image file";
        delete file;
        return;
    }

    QByteArray imageBase64 = file->readAll().toBase64();
    file->close();
    delete file;

    QJsonObject json;
    json["image"] = QString(imageBase64);
    json["image_type"] = "BASE64";
    json["group_id"] = groupId;
    json["user_id"] = userId;
    json["user_info"] = userInfo;
    QJsonDocument jsonDoc(json);
    QByteArray postData = jsonDoc.toJson();

    QNetworkReply *reply = manager->post(QNetworkRequest(url), postData);

    QEventLoop loop;
    connect(reply, &QNetworkReply::finished, &loop, &QEventLoop::quit);
    loop.exec();

    if (reply->error() == QNetworkReply::NoError) {
        QString response = reply->readAll();
        qDebug() << "Update Response:" << response;
    } else {
        qDebug() << "Error updating face:" << reply->errorString();
    }

    reply->deleteLater();
}

// 查询人脸库中的信息
void Widget::queryFace(const QString &accessToken, const QString &userId, const QString &groupId)
{
    QUrl url("https://aip.baidubce.com/rest/2.0/face/v3/faceset/user/get");
    QUrlQuery query;
    query.addQueryItem("access_token", accessToken);
    query.addQueryItem("user_id", userId);
    query.addQueryItem("group_id", groupId);
    url.setQuery(query);

    QNetworkReply *reply = manager->get(QNetworkRequest(url));

    QEventLoop loop;
    connect(reply, &QNetworkReply::finished, &loop, &QEventLoop::quit);
    loop.exec();

    if (reply->error() == QNetworkReply::NoError) {
        QString response = reply->readAll();
        qDebug() << "Query Response:" << response;
    } else {
        qDebug() << "Error querying face:" << reply->errorString();
    }

    reply->deleteLater();
}

// 删除人脸库中的信息
void Widget::deleteFace(const QString &accessToken, const QString &userId, const QString &groupId)
{
    QUrl url("https://aip.baidubce.com/rest/2.0/face/v3/faceset/user/delete");
    QUrlQuery query;
    query.addQueryItem("access_token", accessToken);
    query.addQueryItem("user_id", userId);
    query.addQueryItem("group_id", groupId);
    url.setQuery(query);

    QNetworkReply *reply = manager->get(QNetworkRequest(url));

    QEventLoop loop;
    connect(reply, &QNetworkReply::finished, &loop, &QEventLoop::quit);
    loop.exec();

    if (reply->error() == QNetworkReply::NoError) {
        QString response = reply->readAll();
        qDebug() << "Delete Response:" << response;
    } else {
        qDebug() << "Error deleting face:" << reply->errorString();
    }

    reply->deleteLater();
}
// 点击按钮逻辑
void Widget::on_button_enter_clicked()
{
    dist = new distinguish(this);
    ui->stackedWidget->removeWidget(att);
    ui->stackedWidget->removeWidget(mass);
    ui->stackedWidget->addWidget(dist);
    ui->stackedWidget->setCurrentWidget(dist);
}

void Widget::on_button_person_clicked()
{
    mass = new massage(this);
    ui->stackedWidget->removeWidget(dist);
    ui->stackedWidget->addWidget(mass);
    ui->stackedWidget->setCurrentWidget(mass);
}

void Widget::on_button_work_clicked()
{
    att = new attendance(this);
    ui->stackedWidget->removeWidget(dist);
    ui->stackedWidget->removeWidget(mass);
    ui->stackedWidget->addWidget(att);
    ui->stackedWidget->setCurrentWidget(att);
}
